package com.yeziji.devops.business.dataSource.service.impl;

import com.yeziji.common.IServiceImpl;
import com.yeziji.devops.annotation.DevopsService;
import com.yeziji.devops.business.dataSource.dto.DevopsDataSourceOperateDTO;
import com.yeziji.devops.business.dataSource.entity.DevopsDataSourceEntity;
import com.yeziji.devops.business.dataSource.mapper.DevopsDataSourceMapper;
import com.yeziji.devops.business.dataSource.service.DevopsDataSourceService;
import com.yeziji.devops.common.DevopsKey;
import com.yeziji.devops.common.msg.DevopsErrorMsg;
import com.yeziji.utils.expansion.Asserts;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * devops 管理数据源 服务层实现。
 *
 * @author system
 * @since 2024-08-15
 */
@Slf4j
@DevopsService(name = DevopsKey.DataSource.MASTER)
public class DevopsDataSourceServiceImpl extends IServiceImpl<DevopsDataSourceMapper, DevopsDataSourceEntity> implements DevopsDataSourceService {

    @Override
    public boolean saveOrUpdate(DevopsDataSourceOperateDTO operateDTO) {
        DevopsDataSourceEntity entity;
        if (operateDTO.isHasId()) {
            entity = this.getById(operateDTO.getId(), DevopsErrorMsg.DATA_SOURCE_IS_NOT_EXISTS);
            if (operateDTO.isDelete()) {
                return this.removeById(entity);
            }
            // 更新名称
            String name = operateDTO.getName();
            if (!Objects.equals(entity.getName(), name)) {
                Asserts.noExists(this)
                        .eq(DevopsDataSourceEntity::getName, name)
                        .exception(DevopsErrorMsg.DATA_SOURCE_NAME_IS_DUPLICATE);
            }
            entity = operateDTO.convertToEntity();
            return this.updateById(entity);
        } else {
            return Asserts.noExists(this)
                    .eq(DevopsDataSourceEntity::getName, operateDTO.getName())
                    .throwThen(DevopsErrorMsg.DATA_SOURCE_NAME_IS_DUPLICATE, () -> this.save(operateDTO.convertToEntity()));
        }
    }
}
